import { deleteConfig, getTagConfigList, saveConfig, testConfig } from '@/services/tag'
import { ConsoleSqlOutlined } from '@ant-design/icons'
import { EditableProTable, ProForm } from '@ant-design/pro-components'
import { css } from '@emotion/css'
import { Breadcrumb, Button, Input, message, Space, Table, Tag } from 'antd'
import { isArray } from 'lodash'
import React, { useEffect, useState } from 'react'
import router from 'umi/router'

const EntityType = (props) => {
  const TagConfigList = async () => {
    const res = await getTagConfigList({ id: props.id })
    console.log(res)
    if (res.data !== null) {
      res.data.forEach((item, index) => {
        res.data[index].logicChar = item.logicChar.toString()
        res.data[index].expressionType = item.expressionType.toString()
      })
    }
    console.log(res.data)
    setDataSource(res.data === null ? [] : res.data)
  }
  useEffect(() => {
    TagConfigList()
  }, [])
  const [configList, setConfigList] = React.useState(null)
  const [editableKeys, setEditableRowKeys] = React.useState()
  const [dataSource, setDataSource] = React.useState([])
  const [value, setValue] = React.useState(
    '据报道，伦敦号航空母舰今年5月从英国出港,坦克进攻了日本,战斗机群和F战斗机进攻了美国。',
  )
  const actionRef = React.useRef()
  const [rule, setRules] = React.useState()
  const { TextArea } = Input
  const columns = [
    {
      title: '逻辑符',
      dataIndex: 'logicChar',
      width: '30%',
      valueEnum: {
        0: { text: '且' },
        1: { text: '或' },
      },
    },
    {
      title: '规则表达式',
      dataIndex: 'expressionType',
      valueType: 'select',
      formItemProps: {
        rules: [
          {
            validator: async (rules, value, callback) => {
              if (value) {
                setRules(value)
                await callback()
              }
            },
          },
        ],
      },
      valueEnum: {
        0: { text: '已......结尾' },
        1: {
          text: '已......开头',
        },
        2: {
          text: '包含',
        },
        3: {
          text: '不包含',
        },
        4: {
          text: '等于',
        },
        5: {
          text: '不等于',
        },
        6: {
          text: '正则表达式',
        },
      },
    },
    {
      title: '值',
      dataIndex: 'expressionValue',
      formItemProps: {
        rules: [
          {
            message: '必须是正则',
            validator: async (rules, value, callback) => {
              if (value && rule === '6') {
                if (eval(value) instanceof RegExp) {
                  await callback()
                }
                await callback(new Error('必须是正则'))
              }
            },
          },
        ],
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 250,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            console.log(record)
            action?.startEditable?.(record.id)
          }}
        >
          编辑
        </a>,
        //删除
        <a
          key="delete"
          onClick={async () => {
            const res = await deleteConfig({ ids: [record.id] })
            const newConfigList = await getTagConfigList({ id: props.id })
            setDataSource(newConfigList.data === null ? [] : newConfigList.data)
            let rowKeysArrConfig = selectedRowKeys
            let deleteIndex = rowKeysArrConfig.findIndex((predicate) => predicate === record.id)
            rowKeysArrConfig.splice(deleteIndex, 1)
            setSelectedRowKeys(rowKeysArrConfig)
          }}
        >
          删除
        </a>,
      ],
    },
  ]

  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const onSelectChange = (newSelectedRowKeys) => {
    console.log('selectedRowKeys changed: ', selectedRowKeys)
    setSelectedRowKeys(newSelectedRowKeys)
  }

  const resColumns = [
    {
      title: '抽取结果',
      dataIndex: 'span',
      key: 'span',
    },
    {
      title: '标签类型',
      dataIndex: 'type',
      key: 'type',
    },
  ]
  const [data, setData] = useState([])
  const [isArray, setIsArray] = useState(true)
  const annotatedEffects = (value, data) => {
    let strArr = value.split('')
    let flag = 0
    return (
      <>
        {strArr.map((item, index) => {
          if (index >= data[flag]?.start && index <= data[flag]?.end) {
            if (index === data[flag].end) {
              console.log(data[flag].type)
              flag += 1
              return (
                <>
                  <span
                    key={index}
                    style={{
                      backgroundColor: '#2AC4A1',
                      display: 'inline-block',
                      color: '#fff',
                      fontSize: '16px',
                      padding: '2px',
                    }}
                  >
                    {item}
                  </span>
                  <span
                    key={flag.toString()}
                    style={{
                      backgroundColor: '#2AC4A1',
                      display: 'flex',
                      alignItems: 'end',
                      color: '#fff',
                      fontSize: '12px',
                      height: '29px',
                      padding: '2px',
                    }}
                  >
                    {data[flag - 1].type}
                  </span>
                </>
              )
            } else {
              return (
                <span
                  key={index}
                  style={{
                    backgroundColor: '#2AC4A1',
                    display: 'inline-block',
                    color: '#fff',
                    fontSize: '16px',
                    padding: '2px',
                  }}
                >
                  {item}
                </span>
              )
            }
          } else {
            return <span key={index}>{item}</span>
          }
        })}
      </>
    )
  }
  const [isTest, setIsTest] = useState(false)
  return (
    <>
      <div
        style={{
          height: '50px',
          width: '100%',
          backgroundColor: '#ECEFF2',
          display: 'flex',
          alignItems: 'center',
        }}
      >
        <Breadcrumb>
          <Breadcrumb.Item>
            <a
              onClick={() => {
                router.push('/resource/organization/allOrganization')
              }}
            >
              标签管理
            </a>
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            <a
              onClick={() => {
                router.push('/resource/addOrganization')
              }}
            >
              配置
            </a>
          </Breadcrumb.Item>
        </Breadcrumb>
      </div>
      <h1
        style={{
          paddingLeft: '20px',
          height: '100px',
          lineHeight: '100px',
          marginBottom: '0px',
        }}
      >
        规则列表
      </h1>
      <div
        style={{
          padding: '20px',
        }}
      >
        {dataSource ? (
          <ProForm
            // initialValues={configList[0]}
            // onFinish={async (values) => {
            //   console.log(values)
            //   console.log(dataSource)
            //   message.success('提交成功')
            // }}
            submitter={{
              // 配置按钮文本
              searchConfig: {
                resetText: '重置',
                submitText: '提交',
              },
              // 配置按钮的属性
              resetButtonProps: {
                style: {
                  // 隐藏重置按钮
                  display: 'none',
                },
              },
              submitButtonProps: {},

              // 完全自定义整个区域
              render: (props, doms) => {
                console.log(props)
                return []
              },
            }}
            toolBarRender={false}
          >
            {/* <ProForm.Group>
              <ProFormText width="md" name="name" label="标签名称" placeholder="请输入标签" />
              <ProFormText width="md" name="company" label="标签" placeholder="请输入类型" />
              <ProFormText width="sm" name="id" label="词库映射" />
            </ProForm.Group>
            <h3>规则列表</h3> */}
            <Button
              style={{
                marginRight: '10px',
                marginBottom: '20px',
              }}
              type="primary"
              onClick={() => {
                actionRef.current?.addEditRecord?.({
                  id: parseInt((Math.random() * 1000000).toFixed(0)),
                })
              }}
              // icon={<PlusOutlined />}
            >
              新增
            </Button>
            <Button
              style={{
                marginRight: '10px',
                marginBottom: '20px',
              }}
              onClick={async () => {
                const res = await deleteConfig({ ids: selectedRowKeys })
                console.log(res)
                TagConfigList()
                setSelectedRowKeys([])
              }}
            >
              删除
            </Button>
            <Button
              style={{
                marginBottom: '20px',
              }}
              onClick={() => {
                setIsTest(!isTest)
              }}
            >
              测试
            </Button>
            <ProForm.Item name="dataSource" initialValue={dataSource}>
              <EditableProTable
                rowSelection={{
                  // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                  // 注释该行则默认不显示下拉选项
                  selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
                  defaultSelectedRowKeys: [],
                  selectedRowKeys,
                  onChange: onSelectChange,
                }}
                // tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
                //   <Space size={24}>
                //     <span>
                //       已选 {selectedRowKeys.length} 项
                //       <a
                //         style={{ marginInlineStart: 8 }}
                //         onClick={() => {
                //           onCleanSelected()
                //           console.log(selectedRows)
                //         }}
                //       >
                //         取消选择
                //       </a>
                //     </span>
                //   </Space>
                // )}
                controlled
                rowKey="id"
                toolBarRender={false}
                actionRef={actionRef}
                onChange={(value) => {
                  setDataSource(value)
                }}
                // 关闭默认的新建按钮
                recordCreatorProps={false}
                columns={columns}
                value={dataSource}
                editable={{
                  editableKeys,
                  onChange: (keys, row) => {
                    setEditableRowKeys([...keys])
                  },
                  onSave: async (key, row) => {
                    console.log(typeof row.id)
                    const res = await saveConfig({
                      mappingId: props.id,
                      logicChar: parseInt(row.logicChar),
                      expressionType: parseInt(row.expressionType),
                      expressionValue: row.expressionValue,
                      id: typeof row.id === 'number' ? null : row.id,
                    })
                    TagConfigList()
                    console.log(res)
                  },
                  onDelete: async (key, row) => {
                    let rowKeysArrConfig = selectedRowKeys
                    let deleteIndex = rowKeysArrConfig.findIndex((predicate) => predicate === row.id)
                    rowKeysArrConfig.splice(deleteIndex, 1)
                    setSelectedRowKeys(rowKeysArrConfig)
                  },
                  actionRender: (row, config, dom) => {
                    return [dom.save, dom.cancel]
                  },
                }}
              />
            </ProForm.Item>
          </ProForm>
        ) : null}
        {isTest ? (
          <>
            <div
              className={css`
                width: 100%;
                display: flex;
                justify-content: space-between;
              `}
            >
              <div
                className={css`
                  width: 47%;
                `}
              >
                {isArray ? (
                  <TextArea
                    value={value}
                    onChange={(e) => setValue(e.target.value)}
                    placeholder="Controlled autosize"
                    autoSize={{
                      minRows: 15,
                      maxRows: 20,
                    }}
                  />
                ) : (
                  <div
                    style={{
                      minHeight: '400px',
                      display: 'flex',
                      flexWrap: 'wrap',
                      alignItems: 'start',
                      border: '1px solid #d9d9d9',
                    }}
                  >
                    {annotatedEffects(value, data)}
                  </div>
                )}
              </div>
              <div
                className={css`
                  width: 47%;
                  border: 1px solid #d9d9d9;
                `}
              >
                <Table columns={resColumns} dataSource={data} />
              </div>
            </div>
            <div
              className={css`
                margin: 20px;
              `}
            >
              <Button
                style={{
                  marginRight: '10px',
                }}
                type="primary"
                onClick={async () => {
                  const res = await testConfig({ ids: selectedRowKeys, content: value })
                  if (res.retCode === '0') {
                    res.data.forEach((item, index) => {
                      res.data[index].key = index
                    })
                    setData(res.data)
                    setIsArray(false)
                  } else {
                    message.error('请输入文本并选择规则')
                    setData([])
                  }
                }}
              >
                规则抽取
              </Button>
              <Button
                style={{
                  marginRight: '10px',
                }}
                onClick={() => {
                  setIsArray(true)
                }}
              >
                编辑
              </Button>
              <Button
                style={{
                  marginRight: '10px',
                }}
                onClick={() => {
                  setValue('')
                  setIsArray(true)
                }}
              >
                清空
              </Button>
            </div>
          </>
        ) : null}
      </div>
    </>
  )
}
export default EntityType
